
package com.joysuch.wwyt.mh.controller;

import com.joysuch.wwyt.core.common.ajax.ResultBean;
import com.joysuch.wwyt.core.exception.ApiBusinessException;
import com.joysuch.wwyt.core.support.Context;
import com.joysuch.wwyt.mh.bean.*;
import com.joysuch.wwyt.mh.dto.MhMonitoringPointDto;
import com.joysuch.wwyt.mh.entity.MhMonitoringPoint;
import com.joysuch.wwyt.mh.service.MhMonitoringPointService;
import com.joysuch.wwyt.mh.service.MonitorPointDataWebSocketService;
import com.joysuch.wwyt.mh.storage.IMonitorPointDataService;
import com.joysuch.wwyt.mh.storage.MonitorPointData;
import com.joysuch.wwyt.mh.storage.task.MonitorPointDataExtractTask;
import com.joysuch.wwyt.risk.service.impl.RiskEvaluationPlanServiceImpl;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.util.Assert;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.File;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.Date;
import java.util.List;
import java.util.Optional;

@RestController
@RequestMapping("/mh/monitoring-point")
@Api(tags = "/mh/monitoring-point监测点")
@Slf4j
public class MhMonitoringPointController {

    @Autowired
    private MhMonitoringPointService mhMonitoringPointService;
    @Autowired
    private IMonitorPointDataService monitorPointDataService;
    @Autowired
    private RiskEvaluationPlanServiceImpl service;
    @Autowired
    private MonitorPointDataWebSocketService monitorPointDataWebSocketService;

    @Value("${wwyt.base.serverUrl}")
    private String serverUrl;
    @Value("${wwyt.image.upload.dir}")
    private String imageUploadDir;
    @Value("${wwyt.file.upload.dir}")
    private String fileUploadDir;

    @Autowired
    private MonitorPointDataExtractTask extractTask;

    @PostMapping("/save")
    @ApiOperation(value = "增加")
    public ResultBean add(@RequestBody @Valid MhMonitoringPoint mhMonitoringPoint) {
        mhMonitoringPointService.add(mhMonitoringPoint);
        return ResultBean.defaultSuccessResult();
    }

    @PostMapping("/edit")
    @ApiOperation(value = "修改")
    public ResultBean edit(@RequestBody @Valid MhMonitoringPoint mhMonitoringPoint) {
        mhMonitoringPointService.edit(mhMonitoringPoint);
        return ResultBean.defaultSuccessResult();
    }

    @GetMapping("getById")
    public MhMonitoringPointBean mhMonitoringPointBean(Long id) {
        return mhMonitoringPointService.getById(id);
    }

    @GetMapping("/getMhMonitoringPointById")
    @ApiOperation(value = "根据监测点id获取监测点详细信息")
    public ResultBean MhMonitoringPointBeanDto(Long id){
        try {
            MhMonitoringPointDto mhMonitoringPointById = mhMonitoringPointService.getMhMonitoringPointById(id);
            return ResultBean.success(mhMonitoringPointById);
        } catch (ApiBusinessException e) {
            return ResultBean.fail(e.getCode(),e.getMessage());
        }
    }

    @GetMapping("/list")
    @ApiOperation(value = "列表展示")
    public ResultBean list(Pageable page, String name, String pointCode, Long monitoringTypeId, Long categoryId, Integer showFlag, Integer filter) {
        Page<MhMonitoringPointListBean> list = mhMonitoringPointService.list(page, name, pointCode, monitoringTypeId, categoryId, showFlag, filter, null);
        return ResultBean.pageData(list.getContent(), list.getTotalElements());
    }

    /**
     * 切换监测点状态
     *
     * @param id
     * @param state
     * @return
     */
    @GetMapping("/switch")
    public ResultBean switchState(Long id, Integer state) {
        Assert.isTrue(state != null && (state == 1 || state == 0), "状态错误");
        mhMonitoringPointService.changeState(id, state);
        return ResultBean.success(state);
    }

    /**
     * 切换监测点状态(批量)
     *
     * @param bean
     * @return
     */
    @PostMapping("/batchSwitch")
    public ResultBean batchSwitch(@RequestBody MhMonitoringPointReqBean bean){
        mhMonitoringPointService.batchSwitch(bean);
        return ResultBean.success(bean.getState());
    }

    @GetMapping("/page")
    public ResultBean page(Pageable page, String name, String pointCode, Long monitoringTypeId, Long categoryId) {
        Page<MhMonitoringPointListBean> list = mhMonitoringPointService.page(page, name, pointCode, monitoringTypeId, categoryId);
        return ResultBean.pageData(list.getContent(), list.getTotalElements());
    }

    @PostMapping("/value-his")
    @RequiresPermissions("mh:point:value:his")
    public ResultBean valueHis(@RequestBody MonitorPointHistoryQueryBean bean) {
        try {
            List<MonitorPointData> list = monitorPointDataService.historyVals(Context.getCurrentTenantId(),
                    Context.getCompanyCode(), bean.getTag(), bean.getStartTime(), bean.getEndTime(), bean.getFlag());
            return ResultBean.wrapSuccessfulResult(list);
        } catch (Exception e) {
            String platform = bean.getFlag() != null && bean.getFlag() == 0 ? "一体化平台" : "数据中心";
            return ResultBean.fail(404, "连接" + platform + "出错");
        }
    }

    @ResponseBody
    @PostMapping("/value-real")
    public ResultBean valueReal(@RequestBody MonitorPointQueryBean bean) {
        Optional<MonitorPointData> monitorPointData = monitorPointDataService.realTimeVal(Context.getCurrentTenantId(),
                Context.getCompanyCode(), bean.getTag());
        return ResultBean.wrapSuccessfulResult(monitorPointData.orElse(null));
    }

    @RequestMapping("download")
    public void download(HttpServletRequest request, HttpServletResponse response) throws Exception {
        // service.download(response);
        try {
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            // 1.设置文件ContentType类型，这样设置，会自动判断下载文件类型
            // 2.设置文件头：最后一个参数是设置下载文件名(假如我们叫a.pdf)
            String filename = "监测点导入模板.xlsx";
            String agent = request.getHeader("User-Agent");
            if (agent.contains("MSIE")) {
                // IE浏览器
                filename = URLEncoder.encode(filename, "utf-8");
                filename = filename.replace("+", " ");
            } else {
                // 其它浏览器
                filename = URLEncoder.encode(filename, "utf-8");
            }
            response.setHeader("Content-Disposition", "attachment;fileName=" + filename);
            InputStream stream = MhMonitoringPointController.class.getClassLoader()
                    .getResourceAsStream("template/监测点导入模板.xlsx");
            // ClassPathResource resouse = new ClassPathResource();
            if (stream != null) {
                byte[] cache = new byte[2048];
                int len = 0;
                // FileInputStream fis = new FileInputStream(imageFile);
                while ((len = stream.read(cache)) != -1) {
                    response.getOutputStream().write(cache, 0, len);
                }
                // fis.close();
                response.getOutputStream().flush();
            } else {
                response.setStatus(404);
                response.getOutputStream().flush();
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private String getContentType(File imageFile) {
        return "multipart/form-data";
    }

    @RequestMapping("/uploading")
    public ResultBean uploading(MultipartFile file) throws Exception {
        service.uploading(file);
        return ResultBean.defaultSuccessResult();
    }

    @GetMapping("delete")
    @RequiresPermissions("mh:monitoring-point:delete")
    public ResultBean delete(Long id) {
        return mhMonitoringPointService.deleteById(id);
    }

    @GetMapping("deletePoints")
    @RequiresPermissions("mh:monitoring-point:delete")
    public ResultBean deletePoints(List<Long> ids) {
        mhMonitoringPointService.deletePoints(ids);
        return ResultBean.success("");
    }

    @GetMapping("dataBackup")
    public ResultBean monitorPointDataBackup(HttpServletResponse response, Date startTime, Date endTime) {
        try {
            monitorPointDataService.monitorPointDataBackup(response, startTime, endTime);
            return ResultBean.success("");
        } catch (ApiBusinessException ex) {
            log.error("监测点数据备份失败：", ex);
            return ResultBean.fail(ex.getCode(), ex.getMessage());
        }
    }

    @GetMapping("backupFileSize")
    public ResultBean getMonitorPointBackupFileSize(Date startTime, Date endTime) {
        try {
            return ResultBean.success(monitorPointDataService.getMonitorPointBackupFileSize(startTime, endTime));
        } catch (ApiBusinessException ex) {
            log.error("获取监测点数据信息失败：", ex);
            return ResultBean.fail(ex.getCode(), ex.getMessage());
        }
    }
    @GetMapping("test")
    public void test(Date startTime, Date endTime) {

        monitorPointDataWebSocketService.getPointAlarmMessage(null, "ALL");

    }

    @GetMapping("implement/task")
    public ResultBean  implementTask(){
        extractTask.run();
        return ResultBean.defaultSuccessResult();
    }

}
